package com.kasinf.sample.netty;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;

import java.io.*;
import java.net.Socket;
import java.util.Random;

public class JavaSocketClient {

    public static void main(String[] args) {
        String host = "localhost"; // Netty 服务端地址
        int port = 14001;          // Netty 服务端端口

        try (Socket socket = new Socket(host, port)) {
            OutputStream output = socket.getOutputStream();
            InputStream input = socket.getInputStream();

            // 要发送的消息
            String message = RandomUtil.randomString(10000);
            // 构建10位长度头（右对齐，不足补0）
            String lengthHeader = String.format("%10s", message.length()).replace(' ', '0');
            // 拼接完整报文
            byte[] sendData = (lengthHeader + message).getBytes();

            // 发送数据到 Netty 服务端
            output.write(sendData);
            output.flush();
            System.out.println("已发送消息: " + message);

            // 读取响应的长度头（10位）
            byte[] lengthBuf = new byte[10];
            input.read(lengthBuf);
            String respLengthStr = new String(lengthBuf).trim();
            int respLength = Integer.parseInt(respLengthStr);

            // 读取响应内容
            byte[] respBody = new byte[respLength];
            input.read(respBody);
            String response = new String(respBody);
            System.out.println("收到响应: " + response);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
